<?php
/**
 * swoole 整合框架
 */


$http = new swoole_http_server('0.0.0.0', 8811);

$http->set(
    [
        'enable_static_handler' => true,  //notice is handler, not handle
        'document_root' => '/data/wwwroot/default/live/public/static/',
        'worder_num' => 5 // 5个 worker 进程
    ]
);

$http->on('WorkerStart', function(swoole_server $server, $worder_id){
    // 定义应用目录
    define('APP_PATH', __DIR__ . '/../application/');
    //加载框架里面的文件  worker 进程只需要加载基础文件就行了，真正执行是在 request 中执行
    require __DIR__ . '/../thinkphp/base.php';
});

$http->on('request', function ($request, $response) use($http){

    //全局参数转换
    $_POST = $_GET = $_SERVER = [];
    if(isset($request->server)){
        foreach ($request->server as $k => $v){
            $_SERVER[strtoupper($k)] = $v;
        }
    }
    if (isset($request->header)){
        foreach ($request->header as $k => $v){
            $_HEADER[$k] = $v;
        }
    }
    if (isset($request->get)){
        foreach ($request->get as $k => $v){
            $_GET[$k] = $v;
        }
    }
    if (isset($request->post)){
        foreach ($request->post as $k => $v){
            $_POST[$k] = $v;
        }
    }

    ob_start();
    // 执行应用并响应
    try{
        think\Container::get('app', [defined('APP_PATH') ? APP_PATH : ''])
            ->run()
            ->send();
    }catch (\Exception $e){
        //todo 异常抛出
        throw new \Exception($e->getMessage());
    }

    $res = ob_get_contents();
    ob_end_clean();

    $response->end($res);
    //$http->close(); //注销一次请求，会清空上次的请求。简单粗暴，但会 kill 掉进程，后面会优化这种解决方案
    //不使用这种方式，需要修改 thinkphp 框架
});

$http->start();